#include <memory>
#include <iostream>

class Context;

// 状态接口
class State{
public:
    virtual ~State() = default;
    virtual void handle(Context* context) = 0;
};

// 具体状态A
class ConcreteStateA : public State{
    void handle(Context* context) override;
};

// 具体状态B
class ConcreteStateB : public State{
    void handle(Context* context) override;
};

// 上下文类
class Context{
private:
    std::unique_ptr<State> state;
public:
    Context() : state(std::make_unique<ConcreteStateA>()) {}
    void setState(std::unique_ptr<State> s){
        state = std::move(s);
        std::cout << "State changed." << std::endl;
    }
    void request(){
        state->handle(this);
        std::cout << "Request processed." << std::endl;
    }
};

// 状态转换
void ConcreteStateA::handle(Context* context){
    std::cout << "Heading in State A. Transitioning to state B" << std::endl;
    context->setState(std::make_unique<ConcreteStateB>());
}

void ConcreteStateB::handle(Context* context){
    std::cout << "Heading in State B. Transitioning to state A" << std::endl;
    context->setState(std::make_unique<ConcreteStateA>());
}

int main()
{
    Context context;

    for(int i = 0; i < 5; ++i){
        context.request();
        std::cout << "---" << std::endl;
    }
    return 0;
}